<?php

namespace App\Http\Resources;
use App\Models\Resource as AppResource;
use App\Services\AliVodService;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;

class Resource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $data = parent::toArray($request);
        //这里使用when方法,接收两个参数，参数一为表达式，意思是表达式的值为true，就执行第二个参数，也就是赋值给该字段，为flase则当做不存在
        $data['video'] = $this->when($this->type == AppResource::VIDEO,$this->video); 
        
        // 如果是视频类型资源，获取并添加阿里云播放凭证
        if ($this->type == AppResource::VIDEO && isset($this->video) && $this->video && !empty($this->video->ali_id)) {
            try {
                $vodService = new AliVodService();
                $playAuth = $vodService->getPlayAuth($this->video->ali_id);
                
                // 添加播放凭证字段
                $data['video_play_auth'] = $playAuth;
                
                // 获取播放地址信息
                $playInfo = $vodService->getPlayInfo($this->video->ali_id, [
                    'formats' => 'mp4,m3u8', // 获取mp4和m3u8格式
                    'authTimeout' => 3600, // 地址有效期1小时
                ]);
                
                // 记录获取播放地址的日志
                if ($playInfo) {
                    Log::info('成功获取视频播放地址', [
                        'resource_id' => $this->id,
                        'video_id' => $this->video->id,
                        'ali_id' => $this->video->ali_id,
                        'play_info_count' => count($playInfo['PlayInfoList']['PlayInfo'] ?? [])
                    ]);
                    
                    // 提取可直接播放的URL
                    $playUrls = [];
                    if (isset($playInfo['PlayInfoList']['PlayInfo']) && is_array($playInfo['PlayInfoList']['PlayInfo'])) {
                        foreach ($playInfo['PlayInfoList']['PlayInfo'] as $info) {
                            if (isset($info['PlayURL'])) {
                                $format = $info['Format'] ?? 'unknown';
                                $definition = $info['Definition'] ?? '';
                                $playUrls[$format . '_' . $definition] = $info['PlayURL'];
                            }
                        }
                    }
                    
                    // 添加到返回数据中
                    $data['video_play_info'] = [
                        'VideoId' => $this->video->ali_id,
                        'PlayAuth' => $playAuth,
                        'HasPlayAuth' => !empty($playAuth),
                        'PlayURLs' => $playUrls,
                        'DirectPlayURL' => $playUrls['m3u8_HD'] ?? $playUrls['m3u8_SD'] ?? $playUrls['m3u8_LD'] ?? ($playUrls['mp4_HD'] ?? $playUrls['mp4_SD'] ?? $playUrls['mp4_LD'] ?? ''),
                    ];
                    
                    // 添加完整的阿里云返回的播放信息
                    $data['aliyun_play_info'] = $playInfo;
                } else {
                    Log::warning('获取视频播放地址失败', [
                        'resource_id' => $this->id,
                        'video_id' => $this->video->id,
                        'ali_id' => $this->video->ali_id
                    ]);
                    
                    // 播放地址获取失败时仍添加基础播放信息
                    $data['video_play_info'] = [
                        'VideoId' => $this->video->ali_id,
                        'PlayAuth' => $playAuth,
                        'HasPlayAuth' => !empty($playAuth),
                        'PlayURLs' => [],
                        'DirectPlayURL' => '',
                        'error' => '无法获取视频播放地址'
                    ];
                }
                
                // 记录成功日志
                if (empty($playAuth)) {
                    Log::warning('获取到空的播放凭证', [
                        'resource_id' => $this->id,
                        'video_id' => $this->video->id,
                        'ali_id' => $this->video->ali_id
                    ]);
                    
                    // 提供错误说明
                    if (isset($data['video_play_info'])) {
                        $data['video_play_info']['error'] = '无法获取有效的播放凭证';
                    }
                }
            } catch (\Exception $e) {
                Log::error('获取视频播放信息异常', [
                    'resource_id' => $this->id,
                    'video_id' => $this->video->id,
                    'ali_id' => $this->video->ali_id,
                    'error' => $e->getMessage()
                ]);
                
                // 出错时提供基本信息
                $data['video_play_auth'] = '';
                $data['video_play_info'] = [
                    'VideoId' => $this->video->ali_id,
                    'PlayAuth' => '',
                    'HasPlayAuth' => false,
                    'PlayURLs' => [],
                    'DirectPlayURL' => '',
                    'error' => '获取播放信息时发生错误: ' . $e->getMessage()
                ];
            }
        }
        
        $data['doc'] = $this->when($this->type == AppResource::DOC,$this->doc);
        $data['xmdesc'] = "该接口由XiaoMing使用laravel进行开发，请合理使用！";

        return $data;
    }
}
